const express = require('express');
const router = express.Router();
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const co = require('co');

const DB = require('../db');
const DT = require('../lib/dt');
const EJS = require('../lib/ejs');
// 列表和搜索
router.get('/', function (req, res, next) {
    co(function* () {
        const page = req.query.page || 1;
        const rows = req.query.rows || 10;
        const words = req.query.words || '';
        const data = yield DB.Person.findAndCountAll({
            raw: true,
            where: {
                name: {
                    [Op.substring]: words,
                },
            },
            order: [
                ['id', 'desc'],
            ],
            limit: rows,
            offset: (page - 1) * rows,
        });
        res.render('person', {page: parseInt(page), rows: parseInt(rows), words: words, data: data});
    }).catch((err) => {
        next(err);
    });
});
// 修改或新增
router.get('/to/:id', function (req, res, next) {
    co(function* () {
        const page = req.query.page || 1;
        const rows = req.query.rows || 10;
        const words = req.query.words || '';
        let person = {f: {}, m: {}, x: {}};
        let nongDayCount, nong = `${DT.today.nongY}-${DT.today.nongM}-`; // 当前农历月有多少天，默认按今天查
        if (req.params.id > 0) {
            let data = yield DB.Person.findByPk(req.params.id, {raw: true});
            nong = data.nong.substring(0, data.nong.lastIndexOf('-') + 1);
            person = EJS.person(data);
            if (person.fid) {
                let data = yield DB.Person.findByPk(person.fid, {raw: true});
                person.f = EJS.person(data);
            }
            if (person.mid) {
                let data = yield DB.Person.findByPk(person.mid, {raw: true});
                person.m = EJS.person(data);
            }
            if (person.xid) {
                let data = yield DB.Person.findByPk(person.xid, {raw: true});
                person.x = EJS.person(data);
            }
        }
        nongDayCount = yield DB.Calendar.count({
            raw: true,
            where: {
                nong: {
                    [Op.startsWith]: DT.simple(nong),
                }
            },
        });
        res.render('person_edit', {
            page: parseInt(page),
            rows: parseInt(rows),
            words: words,
            person: person,
            nongDayCount: nongDayCount
        });
    }).catch((err) => {
        next(err)
    })
});
// 搜索
router.post('/find', function (req, res, next) {
    co(function* () {
        const words = req.body.words || '';
        const data = yield DB.Person.findAll({
            raw: true,
            limit: 10,
            where: {
                name: {
                    [Op.substring]: words,
                },
            }
        });
        res.json(data.map((v) => EJS.person(v)));
    }).catch((err) => {
        next(err)
    })
})
// 保存
router.post('/save', function (req, res, next) {
    const id = req.int('id');
    const me = {
        fid: req.int('fid'),
        mid: req.int('mid'),
        xid: req.int('xid'),
        name: req.body.name,
        sex: req.body.sex,
        gong: DT.full(req.body.gong),
        nong: DT.full(req.body.nong),
        nian: req.body.nian,
    };
    if (me.fid + me.mid + me.xid === 0) {
        res.end('父亲、母亲、配偶至少选择一项！');
        return;
    }
    co(function* () {
        if (id) {
            const count = yield DB.Person.update(me, {where: {id: id}});
            if (count > 0) {
                if (me.xid) {
                    const count = yield DB.update('update person set xid=? where id=? and xid=0', [id, me.xid]);
                }
                res.json(me);
            } else {
                res.end('没有找到！');
            }
        } else {
            const me = yield DB.Person.create(me);
            res.json(me);
        }
    }).catch((err) => {
        next(err)
    })
});
// 删除
router.post('/del/:id', function (req, res, next) {
    const id = req.int('id');
    if (id <= 0) {
        res.end('ID错误！');
        return;
    }
    co(function* () {
        const me = yield DB.Person.findByPk(id);
        if (!me) {
            res.end('没有找到！');
            return;
        }
        const parent = [me.id];
        let ar;
        if (me.xid) {
            ar = yield DB.Person.findByPk(me.xid);
            parent.push(ar.id);
        }
        const child = yield DB.query('select distinct * from person where fid in ($1) or mid in ($1)', [parent, parent]);
        if (child.length > 0) {
            res.end(`${me.name}和${ar.name}有${child.length}孩子${child.map((i) => i.name).join('、')}，不能删除！`);
            return;
        }
        me.destroy();
        if (ar) {
            ar.xid = 0;
            ar.save();
        }
        res.json(me);
    }).catch((err) => {
        next(err)
    })
});

module.exports = router;